package HBFailureService;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransportException;
import org.ini4j.Ini;

import Node.TMultiplexedProtocol;
import Node.TransportLayer;
import TopologyService.Topology;

public class HBClient implements Runnable{
	
	private int intervalSec;

	private int heartbeatSendCount = 0;
	private Topology topology;
	
	public HBClient(Topology topology, int timeout){
	    
		this.topology = topology;
		intervalSec =  timeout;
		
	}
	
	public void sendHB(String server, int port) throws TException{
		
		TSocket socket = new TSocket(server, port);
		TBinaryProtocol protocol = new TBinaryProtocol(socket);
		TMultiplexedProtocol mp = new TMultiplexedProtocol(protocol, "HBFailureService");
		HBFailureService.Client HBProto = new HBFailureService.Client(mp);
		socket.open();
		HeartBeat beat = new HeartBeat(Integer.toString(topology.myID()), 1);
		HBProto.beat(beat);
		socket.close();	
	}
	
	public void run() {

		// Start heart beat loop, send heart be every intervalSec
		System.out.println("Process " + topology.myID() + " Starting heart beat protocol");
		
		while(true){
		    // Increment send count
            heartbeatSendCount++;
            
            // Get the current time
	        Date date = new Date();
	        SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
	        String current_time = format.format(date);
			try{

				System.out.println("Process " + topology.myID() + " sending heart beat(" + heartbeatSendCount + ") to " + topology.getNextID() + " " + current_time);
    	        sendHB(topology.getNextIP(), topology.getNextPort());
		
			} catch(TTransportException e){
				System.out.println("Process " + topology.myID() + " failed to connect to process " + topology.getNextID());
				topology.failureDetected(topology.getNextID());
			} catch (TException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try{

				System.out.println("Process " + topology.myID() + " sending heart beat(" + heartbeatSendCount + ") to " + topology.getPrevID() + " " + current_time);
    	        sendHB(topology.getPrevIP(), topology.getPrevPort());
		
			} catch(TTransportException e){
				System.out.println("Process " + topology.myID() + " failed to connect to process " + topology.getPrevID());
				topology.failureDetected(topology.getPrevID());
			} catch (TException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
			try {
				Thread.sleep(this.intervalSec * 1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}


}
